#include <QFileDialog>
#include <QPushButton>

#include <QtCrypto>

#include "cstartdialog.h"
#include "ui_cstartdialog.h"

CStartDialog::CStartDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CStartDialog)
{
    ui->setupUi(this);

    QCA::ProviderList qcaProviders = QCA::providers();

    QStringList ciphers;
    foreach(QCA::Provider *p, qcaProviders)
    {
        QStringList list = QCA::Cipher::supportedTypes(p->name()).filter(QRegExp("cbc-pkcs7$"));
        debug(list.join("\n"));
        ciphers.append(list);
    }

    ciphers.replaceInStrings("-cbc-pkcs7", "");

    QVBoxLayout *vbox = new QVBoxLayout;
    foreach(QString str, ciphers)
    {
        QRadioButton *btn = new QRadioButton(str, ui->cipherBox);
        if(str=="aes192")
        {
            btn->setChecked(true);
            //btn->setText(tr("%1 (Default)").arg(str));
        }
        vbox->addWidget(btn);
        m_buttons.append(btn);
    }

    bool not_checked = true;
    foreach(QRadioButton *btn, m_buttons)
        not_checked = not_checked && (!btn->isChecked());

    if(m_buttons.count() && not_checked)
    {
        m_buttons.at(0)->setChecked(true);
        m_buttons.at(0)->setText(tr("%1 (Default)").arg(m_buttons.at(0)->text()));
    }

    ui->cipherBox->setLayout(vbox);

    connect(ui->browseBtn, SIGNAL(clicked()), this, SLOT(open()));

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
}

CStartDialog::~CStartDialog()
{
    delete ui;
}

void CStartDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void CStartDialog::open()
{
    QString filename;
    if(ui->openBtn->isChecked())
        filename = QFileDialog::getOpenFileName(this, tr("Choose already saved database"), "", "Passworder database (*.dbp)");
    else
        filename = QFileDialog::getSaveFileName(this, tr("Choose filename to save database"), "", "Passworder database (*.dbp)");

    if(filename.length())
    {
        if(!filename.endsWith(".dbp"))
            filename += ".dbp";

        ui->pathEdit->setText(filename);

        ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
    }
}

bool CStartDialog::isCreate()
{
    return ui->createBtn->isChecked();
}

QString CStartDialog::filename()
{
    return ui->pathEdit->text();
}

QString CStartDialog::cipher()
{
    foreach(QRadioButton *btn, m_buttons)
        if(btn->isChecked())
            return btn->text();

    return QString();
}
